Find frame rate (frames per second-fps) in OpenCV (Python/C++)
Satya Mallick
November 12, 2015
21 Comments
OpenCV OpenCV Beginners OpenCV Tutorials
November 12, 2015 By 21 Comments
In OpenCV the class VideoCapture handles reading videos and grabbing frames from connected cameras. There is a lot of information you can find about the video file you are playing by using the get(PROPERTY_NAME) method in VideoCapture. One of the common properties you may want to know is to find frame rate or frames per second. You can download all code and example images used in this post here.
This post has been tested on OpenCV 4.2.
How to find frame rate of a camera / webcam in OpenCV ?
In OpenCV finding the frame rate of a connected camera / webcam is not straight forward. The documentation says that get(CAP_PROP_FPS) or get(CV_CAP_PROP_FPS) gives the frames per second. Now that is true for video files, but not for webcams. For webcams and many other connected cameras, you have to calculate the frames per second manually. You can read a certain number of frames from the video and see how much time has elapsed to calculate frames per second.
Download Code
To easily follow along this tutorial, please download code by clicking on the button below. It's FREE!
Download Code
Click here to download the source code to this post
Python
#!/usr/bin/env python
import cv2
import time
if __name__ == '__main__' :
# Start default camera
video = cv2.VideoCapture(0);
# Find OpenCV version
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
# With webcam get(CV_CAP_PROP_FPS) does not work.
# Let's see for ourselves.
if int(major_ver) < 3 :
fps = video.get(cv2.cv.CV_CAP_PROP_FPS)
print("Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps))
else :
fps = video.get(cv2.CAP_PROP_FPS)
print("Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps))
# Number of frames to capture
num_frames = 120;
print("Capturing {0} frames".format(num_frames))
# Start time
start = time.time()
# Grab a few frames
for i in range(0, num_frames) :
ret, frame = video.read()
# End time
end = time.time()
# Time elapsed
seconds = end - start
print ("Time taken : {0} seconds".format(seconds))
# Calculate frames per second
fps = num_frames / seconds
print("Estimated frames per second : {0}".format(fps))
# Release video
video.release()
C++
#include "opencv2/opencv.hpp"
#include
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// Start default camera
VideoCapture video(0);
// With webcam get(CV_CAP_PROP_FPS) does not work.
// Let's see for ourselves.
// double fps = video.get(CV_CAP_PROP_FPS);
// If you do not care about backward compatibility
// You can use the following instead for OpenCV 3
double fps = video.get(CAP_PROP_FPS);
cout
|